//
//  IntersectionExploreMapViewController.m
//  Portable Traffic Signal Assistor
//
//  Created by Ding on 10/15/12.
//  Copyright (c) 2012 TTU. All rights reserved.
//

#import "IntersectionExploreMapViewController.h"

@interface IntersectionExploreMapViewController ()

@end

@implementation IntersectionExploreMapViewController

@synthesize mapView;
@synthesize agency=_agency;
@synthesize subSystem=_subSystem;
@synthesize intersectionList=_intersectionList;
@synthesize selectedAnnotationView=_selectedAnnotationView;
@synthesize calloutAnnotation=_calloutAnnotation;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self.navigationController setToolbarHidden:NO];
    MKUserTrackingBarButtonItem *buttonItem = [[[MKUserTrackingBarButtonItem alloc] initWithMapView:self.mapView] autorelease];
    UIBarButtonItem *space=[[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:self action:nil] autorelease];
    UIBarButtonItem *typeButton = [[[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemPageCurl target:self action:@selector(changeMapType:)] autorelease];
    CustomizedBarButtonItem *homeButtonItem=[[[CustomizedBarButtonItem alloc] initCustomizedBarButtonItem:[UIImage imageNamed:@"home.png"] target:self action:@selector(goToHome:)] autorelease];
    
    //    [typeButton set]
    self.toolbarItems = [ NSArray arrayWithObjects: homeButtonItem,space, buttonItem,space,typeButton,nil];
    //[ buttonItem release ];
    //    UIBarButtonItem *butstonItem = [[ UIBarButtonItem alloc ] initWithTitle: @"Back"
    //                                                    style: UIBarButtonItemStyleBordered
    //                                                   target: self
    //                                                   action: @selector( goBack:) ];
    //    self.toolbarItems = [ NSArray arrayWithObject: buttonItem ];
    //    [ buttonItem release ];
    
    
    self.mapView.delegate = self;
    locationManager = [[CLLocationManager alloc] init];
    [locationManager setDelegate:self];
    [locationManager setDistanceFilter:kCLDistanceFilterNone];
    [locationManager setDesiredAccuracy:kCLLocationAccuracyBest];
    [self.mapView setShowsUserLocation:YES];
    
    if (!_intersectionList) {
        self.intersectionList=[XMLParser getIntersectionList:self.agency.agencyID subSystemID:self.subSystem.subSystemID];
    }
    MKCoordinateRegion region=self.subSystem.region;
    if (region.center.latitude==0) {
        CLLocationCoordinate2D c={0,0};
        region.center=c;
        for (Intersection *intersection in self.intersectionList) {
            if (intersection.intersectionCoordinate.latitude!=0) {
                region = MKCoordinateRegionMakeWithDistance(intersection.intersectionCoordinate ,5000,5000);
                break;
            }
        }
        
        
        //    = MKCoordinateRegionMakeWithDistance(self.signal.coordinate ,5000,5000);
        if (region.center.latitude==0) {
            region = MKCoordinateRegionMakeWithDistance(locationManager.location.coordinate ,5000,5000);
        }
        
    }
    
    
    
    [self.mapView setRegion:region animated:YES];
    [self.mapView setShowsUserLocation:NO];
    for ( int i=0;i<self.intersectionList.count;i++) {
        Intersection *intersection=[self.intersectionList objectAtIndex:i];
        //        CLLocationCoordinate2D newCoord = region.center;
//        Intersection *intersection=[XMLParser getIntersection:signal.signalID agencyID:self.agency.agencyID subSystemID:self.subSystem.subSystemID];
        if (intersection.intersectionCoordinate.latitude!=0) {
            IntersectionMapPoint *mp = [[[IntersectionMapPoint alloc] initWithCoordinate:intersection.intersectionCoordinate agency:self.agency subSystem:self.subSystem intersection:intersection] autorelease];
            
            mp.tag=i;
            
            
            [self.mapView addAnnotation:mp];
        }
        
        
    }
    
    
    
    // Do any additional setup after loading the view from its nib.
}

- (void)viewDidUnload
{
    [self setMapView:nil];
    [super viewDidUnload];
    self.agency=nil;
    self.subSystem=nil;
//    self.timingPattern=nil;
    self.intersectionList=nil;
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
    self.selectedAnnotationView=nil;
    self.calloutAnnotation=nil;
    
}

- (void)viewWillDisappear:(BOOL)animated
{
//    [PropertyReadingWritingClass writeMapRegionToPropertyFile:mapView.region];
    //    [self.navigationController setToolbarHidden:YES];
    self.subSystem.region=self.mapView.region;
    [XMLParser updateSubSystem:self.subSystem agencyID:self.agency.agencyID];
}


-(void) viewWillAppear:(BOOL)animated
{
    //    [self.navigationController setToolbarHidden:NO];
    [super viewWillAppear:animated];
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

- (void) goBack:(id)sender
{
    
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)dealloc {
    [mapView release];
    [_agency release];
    [_subSystem release];
//    [_timingPattern release];
    [_intersectionList release];
    [super dealloc];
}

- (void)mapView:(MKMapView *)theMapView didUpdateUserLocation:(MKUserLocation *)userLocation
{
    //    [theMapView setCenterCoordinate:userLocation.location.coordinate animated:YES];
    //    CLLocationCoordinate2D userCoordinate = userLocation.location.coordinate;
    //    for(int i = 1; i<=5;i++)
    //    {
    //        CGFloat latDelta = rand()*.035/RAND_MAX -.02;
    //        CGFloat longDelta = rand()*.03/RAND_MAX -.015;
    //        CLLocationCoordinate2D newCoord = { userCoordinate.latitude + latDelta, userCoordinate.longitude + longDelta };
    //        MapPoint *mp = [[MapPoint alloc] initWithCoordinate:newCoord title:[NSString stringWithFormat:@"Azam Home %d",i] subTitle:@"Home Sweet Home"];
    //        [theMapView addAnnotation:mp];
    //        [mp release];
    //
    //    }
    
}

- (void)mapView:(MKMapView *)mv didAddAnnotationViews:(NSArray *)views
{
    CGRect visibleRect = [mapView annotationVisibleRect];
    
    for(MKAnnotationView *view in views)
    {
        if([view isKindOfClass:[SignalAnnotationView class]])
        {
            CGRect endFrame = view.frame;
            CGRect startFrame = endFrame;
            startFrame.origin.y = visibleRect.origin.y - startFrame.size.height;
            view.frame = startFrame;
            //            [UIView beginAnimations:@"drop" context:NULL];
            //            [UIView setAnimationDuration:0.5];
            view.frame = endFrame;
            [UIView commitAnimations];
        }
    }
    //    MKAnnotationView *annotationView = [views objectAtIndex:0];
    //    id<MKAnnotation> mp = [annotationView annotation];
    //    MKCoordinateRegion region = MKCoordinateRegionMakeWithDistance([mp coordinate] ,5000,5000);
    //    MKCoordinateRegion region=[PropertyReadingWritingClass readMapRegionFromPropertyFile];
    //    if (region.center.latitude==0) {
    //        region = MKCoordinateRegionMakeWithDistance([mp coordinate] ,5000,5000);
    //    }
    //    [mv setRegion:region animated:YES];
    
}

- (MKAnnotationView *)mapView:(MKMapView *)mv viewForAnnotation:(id <MKAnnotation>)annotation
{
    
    if (annotation == self.calloutAnnotation) {
       
        NSArray *timingPatternList=[XMLParser getTimingPatternList:self.calloutAnnotation.agency.agencyID subSystemID:self.calloutAnnotation.subSystem.subSystemID];
        int height=25+20+10+timingPatternList.count*20;
        CalloutMapAnnotationView * calloutMapAnnotationView = [[[CalloutMapAnnotationView alloc] initWithAnnotation:annotation
                                                                                                    reuseIdentifier:@"CalloutAnnotation" contentWidth:180 contentHeight:height] autorelease];
//        calloutMapAnnotationView.backgroundColor=[UIColor blueColor];
        
        
        IntersectionCalloutContentView * contentView=[[[IntersectionCalloutContentView alloc] initWithFrameAndAnnoation:CGRectMake(5, 2, calloutMapAnnotationView.contentWidth-10, calloutMapAnnotationView.contentHeight-4) annoation:annotation viewController:self] autorelease];
        [calloutMapAnnotationView.contentView addSubview:contentView];
        //		}
		calloutMapAnnotationView.parentAnnotationView = self.selectedAnnotationView;
		calloutMapAnnotationView.mapView = self.mapView;
		return calloutMapAnnotationView;
	}else if ([annotation isKindOfClass:[IntersectionMapPoint class]]) {
        NSString *annotationIdentifier = @"SignalViewAnnotation";
        //    SignalAnnotationView *pinView = (SignalAnnotationView *) [mapView dequeueReusableAnnotationViewWithIdentifier:annotationIdentifier];
        //    if (!pinView)
        //    {
        SignalAnnotationView *pinView = [[[SignalAnnotationView alloc]                     initWithAnnotation:annotation
                                                                                              reuseIdentifier:annotationIdentifier] autorelease];
		pinView.canShowCallout = NO;
        //		annotationView.pinColor = MKPinAnnotationColorGreen;
		return pinView;
	} 
    
    
    //    NSLog(@"%@",ann)
    if([annotation isKindOfClass:[MKUserLocation class]])
        return nil;
    NSString *annotationIdentifier = @"SignalViewAnnotation";
    //    SignalAnnotationView *pinView = (SignalAnnotationView *) [mapView dequeueReusableAnnotationViewWithIdentifier:annotationIdentifier];
    //    if (!pinView)
    //    {
    SignalAnnotationView *pinView = [[[SignalAnnotationView alloc]                     initWithAnnotation:annotation
                                                                                          reuseIdentifier:annotationIdentifier] autorelease];
    
    //        [pinView setPinColor:MKPinAnnotationColorGreen];
    //        pinView.animatesDrop = YES;
    pinView.canShowCallout = YES;
    
    UIImageView *houseIconView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"green_signal.png"]];
    [houseIconView setFrame:CGRectMake(0, 0, 15, 30)];
    pinView.leftCalloutAccessoryView = houseIconView;
    UIButton *detailButton=[UIButton buttonWithType:UIButtonTypeDetailDisclosure];
    //    int testtag=[(MapPoint *)annotation tag];
    detailButton.tag=[(IntersectionMapPoint *)annotation tag];
    pinView.rightCalloutAccessoryView=detailButton;
    [houseIconView release];
    //    }
    //    else
    //    {
    //        pinView.annotation = annotation;
    //    }
    pinView.draggable=NO;
    return pinView;
}
- (void)mapView:(MKMapView *)mapView didSelectAnnotationView:(MKAnnotationView *)view {
    if ([view.annotation isKindOfClass:[IntersectionMapPoint class]]) {
        IntersectionMapPoint *mapPoint=view.annotation;
		if (self.calloutAnnotation == nil) {
            
			self.calloutAnnotation = [[[IntersectionCalloutAnnotation alloc] initWithCoordinate:mapPoint.coordinate agency:mapPoint.agency subSystem:mapPoint.subSystem intersection:mapPoint.intersection] autorelease];
		} else {
			self.calloutAnnotation.coordinate= mapPoint.coordinate;
            self.calloutAnnotation.intersection=mapPoint.intersection;
			
		}
        
		[self.mapView addAnnotation:self.calloutAnnotation];
		self.selectedAnnotationView = view;
	}
}
- (void)mapView:(MKMapView *)mapView didDeselectAnnotationView:(MKAnnotationView *)view {
    //	if (self.calloutAnnotation && view.annotation == self.customAnnotation) {
    if (self.calloutAnnotation) {
        
		[self.mapView removeAnnotation: self.calloutAnnotation];
	}
}
- (void)mapView:(MKMapView *)mapView
 annotationView:(MKAnnotationView *)annotationView
didChangeDragState:(MKAnnotationViewDragState)newState
   fromOldState:(MKAnnotationViewDragState)oldState
{
    if (newState == MKAnnotationViewDragStateEnding)
    {
        CLLocationCoordinate2D droppedAt = annotationView.annotation.coordinate;
        NSLog(@"dropped at %f,%f", droppedAt.latitude, droppedAt.longitude);
    }
}

- (void) locationManager:(CLLocationManager *)manager
        didUpdateHeading:(CLHeading *)newHeading
{
    float heading = newHeading.magneticHeading; //in degrees
    float headingDegrees = (heading*M_PI/180); //assuming needle points to top of iphone. convert to radians
    self.mapView.transform = CGAffineTransformMakeRotation(headingDegrees);
}

//- (void)mapView:(MKMapView *)mapView regionDidChangeAnimated:(BOOL)animated
//{
//    NSLog(@"Map was moved to %f,%f\n", mapView.region.center.latitude, mapView.region.center.longitude);
//}
- (id)initWithNibNameAndTimingPattern:(NSString *)nibNameOrNil agency:(Agency*)agency subSystem:(SubSystem*)subSystem  bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    self.agency=agency;
    self.subSystem=subSystem;
//    self.timingPattern=timingPattern;
    return self;
}
- (void) changeMapType: (id)sender
{
    if (mapView.mapType == MKMapTypeStandard)
        mapView.mapType = MKMapTypeSatellite;
    else
        mapView.mapType = MKMapTypeStandard;
}
- (void)mapView:(MKMapView *)eMapView annotationView:(MKAnnotationView *)view calloutAccessoryControlTapped:(UIControl *)control
{
    //    NSLog(@"%@",control.class);
    NSLog(@"%d",control.tag);
//    SignalDetailViewController *detailViewController=[[[SignalDetailViewController alloc] initWithNibNameAndSignal:@"SignalDetailViewController" agency:self.agency subSystem:self.subSystem timingPattern:self.timingPattern signalList:self.signalList signalIndex:control.tag bundle:nil] autorelease];
//    [detailViewController setTitle:@"Signal Detail"];
//    [self.navigationController pushViewController:detailViewController animated:YES];
//    [self.navigationController setNavigationBarHidden:NO animated:YES];
    
}

- (void) goToHome:(id)sender
{
    [self.navigationController popToRootViewControllerAnimated:YES];
}



@end
